package com.learnyou.server.xingzuo.biz.impl;

import cn.hutool.json.JSON;
import com.google.gson.Gson;
import com.learnyou.server.xingzuo.biz.StorageBiz;
import com.learnyou.server.xingzuo.dao.repository.entity.Storage;
import com.learnyou.server.xingzuo.dao.repository.service.IStorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

@Slf4j
@Service
public class StorageBizImpl implements StorageBiz {

    @Resource
    private IStorageService storageService;

    @Override
    public String getStorageValue(String storageKey) {

        Storage storage = storageService.getStorageByKey(storageKey);
        return Objects.isNull(storage)? null : storage.getStorageValue();
    }

    @Override
    public int upsertStorage(String storageKey, Object value) {
        int affectedRows = 0;
        if (Objects.nonNull(value))  {
            String jsonString;
            if(value instanceof String) {
                jsonString = value.toString();
            } else {
                jsonString = new Gson().toJson(value);
            }
            Storage storage = storageService.upsertStorage(storageKey, jsonString);
            affectedRows = Objects.isNull(storage)? 0 : 1;
        } else {
            log.warn("storage value is empty.");
        }
        return affectedRows;
    }
}
